package cn.itrip.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.pojo.ItripUserLinkUser;
import cn.itrip.beans.vo.order.ItripAddHotelOrderVO;
import cn.itrip.common.*;
import cn.itrip.service.hotelorder.ItripHotelOrderService;
import cn.itrip.service.hoteltempstore.ItripHotelTempStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Api(value = "API", basePath = "/http://api.itrap.com/api")
@RequestMapping(value = "/api/hotelorder")
public class HotelOrderController {

    private Logger logger = Logger.getLogger(HotelOrderController.class);

    @Resource
    private ItripHotelTempStoreService itripHotelTempStoreService;
    @Resource
    private SystemConfig systemConfig;

    @Resource
    private ItripHotelOrderService itripHotelOrderService;

    @ApiOperation(value = "生成订单", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "生成订单" +
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>" +
            "<p>100505 : 生成订单失败 </p>" +
            "<p>100506 : 不能提交空，请填写订单信息 </p>" +
            "<p>100507 : 库存不足 </p>" +
            "<p>100000 : token失效，请重登录</p>")
    @RequestMapping(value = "/addhotelorder", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Object> addHotelOrder(@RequestBody ItripAddHotelOrderVO itripAddHotelOrderVO, HttpServletRequest request) {
        Dto<Object> dto = new Dto<Object>();
        if(null == itripAddHotelOrderVO){
            return DtoUtil.returnFail("不能提交空，请填写订单信息", "100506");
        }
        //骚操作开始
        ItripUser currentUser = new ItripUser();
        currentUser.setId((long)12);

          String tokenString = "";//request.getHeader("token");
//        logger.debug("token name is from header : " + tokenString);
//        ItripUser currentUser = validationToken.getCurrentUser(tokenString);

        //骚操作结束

        //获取表单中的联系人
        List<ItripUserLinkUser> linkUserList = itripAddHotelOrderVO.getLinkUser();

        //判断用户是否为空（为空表示未登录）
        if(EmptyUtils.isEmpty(currentUser)){
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        //判断库存是否充足的入参
        Map<String, Object> validateStoreMap = new HashMap<String, Object>();
        validateStoreMap.put("startTime", itripAddHotelOrderVO.getCheckInDate());
        validateStoreMap.put("endTime", itripAddHotelOrderVO.getCheckOutDate());
        validateStoreMap.put("hotelId", itripAddHotelOrderVO.getHotelId());
        validateStoreMap.put("roomId", itripAddHotelOrderVO.getRoomId());
        validateStoreMap.put("count", itripAddHotelOrderVO.getCount());


        try {
            //判断库存是否充足
            Boolean flag = itripHotelTempStoreService.validateRoomStore(validateStoreMap);

            if (flag) {
                //计算订单的预定天数
                Integer days = DateUtil.getBetweenDates(
                        itripAddHotelOrderVO.getCheckInDate(), itripAddHotelOrderVO.getCheckOutDate()
                ).size()-1;

                if(days<=0){
                    return DtoUtil.returnFail("退房日期必须大于入住日期", "100505");
                }

                ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
                BeanUtils.copyProperties(itripAddHotelOrderVO,itripHotelOrder);
                itripHotelOrder.setUserId(currentUser.getId());
                itripHotelOrder.setCreatedBy(currentUser.getId());

                //编辑联系人姓名 begin
                StringBuilder linkUserName = new StringBuilder();
                int size = linkUserList.size();
                for (int i = 0; i < size; i++) {
                    if (i != size - 1) {
                        linkUserName.append(linkUserList.get(i).getLinkUserName() + ",");
                    } else {
                        linkUserName.append(linkUserList.get(i).getLinkUserName());
                    }
                }
                itripHotelOrder.setLinkUserName(linkUserName.toString());
                //编辑联系人姓名 end

                itripHotelOrder.setBookingDays(days);

                //判断用户客户端
                if (tokenString.startsWith("token:PC")) {
                    itripHotelOrder.setBookType(0);
                } else if (tokenString.startsWith("token:MOBILE")) {
                    itripHotelOrder.setBookType(1);
                } else {
                    itripHotelOrder.setBookType(2);
                }

                //支付之前生成的订单的初始状态为未支付
                itripHotelOrder.setOrderStatus(0);

                try{
                    //订单号处理 begin

                    //生成订单号：机器码 + 日期+（MD5）（商品IDs+毫秒数+1000000的随机数）

                    //服务器机器码，在配置文件中配置
                    String MachineCode = systemConfig.getMachineCode();

                    //日期
                    String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
                    //MD5
                    StringBuilder md5String = new StringBuilder();
                    md5String.append(itripHotelOrder.getHotelId());
                    md5String.append(itripHotelOrder.getRoomId());
                    md5String.append(System.currentTimeMillis());
                    md5String.append(Math.random() * 1000000);
                    String md5 = MD5.getMd5(md5String.toString(), 6);

                    itripHotelOrder.setOrderNo(MachineCode+date+md5);

                    //订单号处理 end

                    //计算订单的总金额
                    BigDecimal payAmount = itripHotelOrderService.getOrderPayAmount(days * itripAddHotelOrderVO.getCount(), itripAddHotelOrderVO.getRoomId());
                    itripHotelOrder.setPayAmount(payAmount);

                    Map<String, String> map = itripHotelOrderService.itriptxAddItripHotelOrder(itripHotelOrder, linkUserList);

                    dto = DtoUtil.returnSuccess("生成订单成功", map);
                } catch (Exception e) {
                    e.printStackTrace();
                    dto = DtoUtil.returnFail("生成订单失败", "100505");
                }

            }  else {
                dto = DtoUtil.returnFail("库存不足", "100507");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100508");
        }
        return dto;
    }
}
